#include "MapEl.h"


MapEl::MapEl(void)
{
	removeIndex = -1;
	sp = NULL;
	shape = NULL;
}


MapEl::~MapEl(void)
{
}

void MapEl::recycle(){
	MapElPool::sharePool()->recycleEl(this);
}

MapElPool::MapElPool()
{
	dic = CCDictionary::create();
	dic->retain();
}

MapElPool::~MapElPool()
{
	dic->release();
}

MapElPool* m_mapElPool = NULL;
MapElPool* MapElPool::sharePool(){
	if(!m_mapElPool){
		m_mapElPool = new MapElPool();
	}
	return m_mapElPool;
}
MapEl* MapElPool::getEl(MapCellType type){
	CCArray* arr = (CCArray*)(dic->objectForKey(type));
	MapEl* el = NULL;
	if(!arr || arr->count() == 0){
		el = new MapEl();
		el->autorelease();
		el->type = type;
		CCSprite* sp = newSpriteByType(type);
		el->sp = sp;
	}else{
		el = (MapEl*)(arr->lastObject());
		arr->removeLastObject(false);
		if(el->sp)el->sp->setVisible(true);
	}
	el->isEate = false;
	return el;
}
CCSprite* MapElPool::newSpriteByType(MapCellType type){
	CCSprite* sp = NULL;
	switch (type)
	{
	case GRESS:
		sp = CCSprite::createWithSpriteFrameName("gress.png");
		break;
	case ROCK:
		sp = CCSprite::createWithSpriteFrameName("rock.png");
		break;
	case TREE1x1:
		sp = CCSprite::createWithSpriteFrameName(CCString::createWithFormat("tree1x1_%d.png",RANG_INT(0,4))->getCString());
		break;
	case TREE2x1:
		sp = CCSprite::createWithSpriteFrameName(CCString::createWithFormat("tree2x1_%d.png",RANG_INT(0,1))->getCString());
		break;
	case TREE2x2:
		sp = CCSprite::createWithSpriteFrameName(CCString::createWithFormat("tree2x2_%d.png",RANG_INT(0,9))->getCString());
		break;
	case TREE3x2:
		sp = CCSprite::createWithSpriteFrameName(CCString::createWithFormat("tree3x2_%d.png",RANG_INT(0,4))->getCString());
		break;
	case STAB:
		sp = CCSprite::createWithSpriteFrameName("trap.png");
		break;
	case FIRE:
		sp = CCSprite::createWithSpriteFrameName("fire.png");
		break;
	case ANIMAL:
		break;
	case POP:
		break;
	case ICE:
		sp = CCSprite::create("ice.png");
		ccTexParams params = {GL_LINEAR,GL_LINEAR,GL_REPEAT,GL_REPEAT};
		sp->getTexture()->setTexParameters(&params);
		break;
	}
	if(sp){
		sp->setAnchorPoint(ccp(0,-10 / sp->getContentSize().height));
	}
	return sp;
}
void MapElPool::recycleEl(MapEl* el){
	if(el->sp){
		el->sp->setVisible(false);
		el->sp->stopAllActions();
	}
	el->isEate = false;
	el->shape = NULL;
	CCArray* arr = (CCArray*)(dic->objectForKey(el->type));
	if(!arr){
		arr = CCArray::create();
		arr->retain();
		dic->setObject(arr,el->type);
	}
	arr->addObject(el);
}
